package server;

import container.Context;
import container.Host;
import container.Mapper;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import servlet.ContextLoader;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.*;

/**
 * Minicat的主类
 */
public class Bootstrap {

    /**定义socket监听的端口号*/
    private int port = 8080;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {

        // 加载解析相关的配置，server.xml
        loadServlet();

        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );

        /*
            完成Minicat 1.0版本
            需求：浏览器请求http://localhost:8080,返回一个固定的字符串到页面"Hello Minicat!"
         */
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);

        System.out.println("=========>>>>>>使用线程池进行多线程改造");
        /*
            多线程改造（使用线程池）
         */
        while(true) {

            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket,mapper);
            //requestProcessor.start();
            threadPoolExecutor.execute(requestProcessor);
        }

    }


    private Mapper mapper = new Mapper();

    /**
     * 加载解析server.xml，初始化Servlet
     */
    private void loadServlet() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            Element connectorElement = (Element)rootElement.selectSingleNode("//Connector");
            String port = connectorElement.attributeValue("port");
            setPort(Integer.valueOf(port));

            List<Element> hostElements = rootElement.selectNodes("//Host");
            for (Element hostElement : hostElements) {

                String hostName = hostElement.attributeValue("name");
                String appBase = hostElement.attributeValue("appBase");

                Host host = new Host(hostName);

                List<Element> contextElements = hostElement.selectNodes("Context");
                if (contextElements != null) {
                    for (Element contextElement : contextElements) {
                        String contextName = contextElement.attributeValue("name");
                        String contextPath = contextElement.attributeValue("path");

                        Context context = new Context(contextName, appBase + "/" + contextPath);
                        ContextLoader contextLoader = new ContextLoader(context);
                        contextLoader.load();

                        host.addContext(context);
                    }
                } else {
                    Context context = new Context("/", appBase);
                    ContextLoader contextLoader = new ContextLoader(context);
                    contextLoader.load();

                    host.addContext(context);
                }

                mapper.addHost(host);

            }

        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }


    /**
     * Minicat 的程序启动入口
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
